package com.nervenets.general.aspect.validate.validator;

import com.nervenets.general.aspect.validate.Unique;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;

public class UniqueValidator implements ConstraintValidator<Unique, Iterable<?>> {
    private boolean nullable;

    @Override
    public void initialize(Unique unique) {
        this.nullable = unique.nullable();
    }

    @Override
    public boolean isValid(Iterable iterable, ConstraintValidatorContext constraintValidatorContext) {
        if (null != iterable) {
            HashSet<Object> objects = new HashSet<>();
            for (Object o : iterable) {
                if (!nullable && null == o) return false;
                if (objects.contains(o)) return false;
                objects.add(o);
            }
        }
        return true;
    }
}
